<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<div class="system-user-search">
				<el-input size="default" class="w_150 mb15 mr10" v-model="listQuery.Name" placeholder="字段名" @keydown.enter="searchForm"> </el-input>

				<el-button size="default" @click="searchForm" type="primary" class="mr10 mb15"> 查询 </el-button>
				<el-button size="default" type="success" class="mr10 mb15" @click="addRule"> 新增 </el-button>
				<el-button size="default" type="info" class="mr10 mb15" @click="resetForm"> 重置 </el-button>
			</div>
			<tableTem ref="tableRef" v-bind:="state.tableData" @pageChange="onTablePageChange">
				<el-table-column align="center" type="index" label="序号" width="60" />
				<el-table-column align="center" min-width="120" prop="destField" label="字段名"></el-table-column>
				<el-table-column align="center" min-width="120" prop="destFieldLable" label="显示名称"></el-table-column>
				<el-table-column align="center" prop="sourceField" min-width="150" label="来源字段名"></el-table-column>
				<el-table-column align="center" prop="plugin" min-width="120" label="插件">
					<template #default="scope">
						{{ getPluginName(scope.row.plugin) }}
					</template>
				</el-table-column>
				<el-table-column align="center" prop="preprocessingParameter" min-width="120" label="插件参数（可选）"></el-table-column>

				<el-table-column label="操作" align="center" width="190" fixed="right">
					<template #default="scope">
						<el-button size="small" type="primary" text @click="editOption(scope.row)">编辑</el-button>
						<el-button size="small" type="primary" text @click="onRowDel(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</tableTem>
		</div>
		<!-- 弹窗 -->
		<el-dialog
			:title="state.isEdit ? '编辑字段' : '新增字段'"
			v-model="state.dialogVisible"
			:close-on-click-modal="false"
			:show-close="false"
			:close-on-press-escape="false"
			width="500px"
		>
			<el-form class="dialog-layout" ref="userForm" :rules="rules" :model="state.ruleForm" size="default" label-width="100px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="插件种类" prop="plugin">
							<div class="flex-c-c">
								<el-select class="w_250 mr10" v-model="state.ruleForm.plugin" size="default">
									<el-option v-for="item in state.plugInList" :key="item.id" :label="item.description" :value="item.pluginName"></el-option>
								</el-select>
								<el-tooltip class="item" effect="dark" placement="right-end">
									<template #content>
										<div>
											插件种类，如 IP转换成地址（将IP地址转换成详细的实际地址），字段合并（将多个原始字段合并起来）
											<br />，字符串截短（例将手机号码截取部分进行筛选，如前七位0,7），等等
										</div>
									</template>
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="目标字段名" prop="destField">
							<div class="flex-c-c">
								<el-input v-model="state.ruleForm.destField" class="w_250 mr10" placeholder="请输入字段名" clearable></el-input>
								<el-tooltip class="item" effect="dark" content="字段显示名称，一般为中文，如'IP归属地'" placement="right-end">
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="显示名称" prop="destFieldLable">
							<el-input v-model="state.ruleForm.destFieldLable" class="w_250 mr10" placeholder="请输入字段名" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
						<el-form-item label="原始字段名" prop="sourceField">
							<div class="flex-c-c">
								<el-select class="w_250 mr10" v-model="state.ruleForm.sourceField" size="default">
									<el-option v-for="item in state.fieldList" :key="item.id" :label="item.fieldName" :value="item.fieldName"></el-option>
								</el-select>
								<el-tooltip class="item" effect="dark" placement="right-end">
									<template #content>
										<div>原始字段名，均为自己定义的字段名</div>
									</template>
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop v-if="state.ruleForm.plugin == 'PhoneNum2Location'">
						<el-form-item label="截取位数" prop="preprocessingParameter">
							<div class="flex-c-c">
								<el-input v-model="state.ruleForm.preprocessingParameter" class="w_250 mr10" placeholder="请输入截取位数" clearable></el-input>
								<el-tooltip
									class="item"
									effect="dark"
									content="截取位数，属于字符串截短插件的参数，如筛选手机号码前7位，填写 0,7"
									placement="right-end"
								>
									<el-icon size="25px" color="#409eff">
										<ele-QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="dialog-btn">
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit(userForm)" size="default">确 认</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import { RiskPluginTypeGetPagedList } from '/@/api/plugInUnit/index';
import { RiskFieldGetPagedList, RiskPreGetPagedList, RiskPreDelete, RiskPreCreate, RiskPreUpdate } from '/@/api/model/index';
// 引入组件
const tableTem = defineAsyncComponent(() => import('/@/components/tables/index.vue'));
// 定义父组件传过来的值
const props = defineProps({
	modelId: {
		type: [Number, String],
		default: () => '',
	},
});
// 定义变量内容
const tableRef = ref();
const listQuery = reactive({
	Name: '', //名称
});
const state = reactive<any>({
	tableData: {
		data: [],
		total: 0,
		loading: true,
		param: {
			PageIndex: 1,
			PageSize: 10,
		},
	},
	fieldList: [], // 原始字段名
	plugInList: [] as any, // 插件种类
	ruleForm: {
		plugin: '', // 插件种类
		destField: '', // 目标字段名
		destFieldLable: '', // 目标字段名
		sourceField: '', // 来源字段
		sourceFieldId: '', // 来源字段id
		sourceFieldLable: '', // 来源字段lable
		preprocessingParameter: '', //预处理参数
		id: '',
	} as any, // 新增
	dialogVisible: false, // 弹窗状态
	isEdit: false, //是否编辑
});
// 页面加载时
onMounted(() => {
	getTableData();
});

// 初始化表格数据
const getTableData = async () => {
	state.tableData.loading = true;
	try {
		const params = {
			...state.tableData.param,
			...listQuery,
			modelId: props.modelId,
		};
		Object.keys(params).forEach((key) => {
			if (!params[key]) delete params[key];
		});
		let data = await RiskPreGetPagedList(params);
		state.tableData.data = data.data.items;
		state.tableData.total = data.data.totalCount;
	} finally {
		state.tableData.loading = false;
	}
};

// 新增
const addRule = () => {
	state.dialogVisible = true;
	state.isEdit = false;
	state.ruleForm.plugin = '';
	state.ruleForm.destField = '';
	state.ruleForm.destFieldLable = '';
	state.ruleForm.sourceField = '';
	state.ruleForm.sourceFieldLable = '';
	state.ruleForm.sourceFieldId = '';
	state.ruleForm.preprocessingParameter = '';
	state.ruleForm.id = '';
	GetFieldTypes();
};
// 编辑
const editOption = (item: any) => {
	GetFieldTypes();
	state.ruleForm.plugin = item.plugin;
	state.ruleForm.destField = item.destField;
	state.ruleForm.destFieldLable = item.destFieldLable;
	state.ruleForm.sourceField = item.sourceField;
	state.ruleForm.sourceFieldLable = item.sourceFieldLable;
	state.ruleForm.sourceFieldId = item.sourceFieldId;
	state.ruleForm.preprocessingParameter = item.preprocessingParameter;
	state.ruleForm.id = item.id;
	state.dialogVisible = true;
	state.isEdit = true;
};

// 删除账户
const onRowDel = (id: any) => {
	ElMessageBox.confirm(`此操作将永久删除预处理信息，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		await RiskPreDelete([id]);
		ElMessage.success('删除成功');
		getTableData();
	});
};
// 分页改变
const onTablePageChange = (val: any) => {
	state.tableData.param.PageIndex = val.pageNum;
	state.tableData.param.PageSize = val.pageSize;
	getTableData();
};
// 搜索点击时表单回调
const searchForm = () => {
	state.tableData.param.PageIndex = 1;
	tableRef.value.pageReset();
};
// 重置
const resetForm = () => {
	listQuery.Name = '';
	searchForm();
};

// 关闭弹窗
const onCancel = () => {
	state.dialogVisible = false;
};
const preprocessingVAlue = (rule: any, value: any, callback: any) => {
	if (!value) {
		callback(new Error('请输入截取位数'));
	} else {
		if (!/^[0-9]*[1-9][0-9]*$/.test(value)) {
			callback(new Error('请输入正整数'));
		} else {
			callback();
		}
	}
};
const rules = reactive({
	plugin: [{ required: true, message: '请选择插件种类', trigger: ['blur', 'change'] }],
	destField: [{ required: true, message: '请输入目标字段名', trigger: ['blur', 'change'] }],
	destFieldLable: [{ required: true, message: '请输入显示名称', trigger: ['blur', 'change'] }],
	sourceField: [{ required: true, message: '请选择来源字段', trigger: ['blur', 'change'] }],
	preprocessingParameter: [{ required: true, validator: preprocessingVAlue, trigger: ['blur', 'change'] }],
});
const userForm = ref<FormInstance>();
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			const params = {
				...state.ruleForm,
				modelId: props.modelId,
			};
			if (params.sourceField && state.fieldList.length) {
				state.fieldList.map((v: any) => {
					if (v.fieldName == params.sourceField) {
						params.sourceFieldLable = v.fieldDisplayName;
						params.sourceFieldId = v.id;
					}
				});
			}
			if (state.isEdit) {
				await RiskPreUpdate(params, state.ruleForm.id);
			} else {
				delete params.id;
				await RiskPreCreate(params);
			}
			ElMessage.success(state.isEdit ? '修改成功' : '新增成功');
			onCancel();
			resetForm();
		}
	});
};
//  原始字段名
const GetFieldTypes = async () => {
	let data = await RiskFieldGetPagedList({
		PageIndex: 1,
		PageSize: 99999,
		modelId: props.modelId,
	});
	state.fieldList = data.data.items;
	let dataPlug = await RiskPluginTypeGetPagedList({
		PageIndex: 1,
		PageSize: 99999,
	});
	state.plugInList = dataPlug.data.items;
};
// 方法，用于获取插件名称
const getPluginName = (pluginId: string) => {
	const pluginInfo = state.plugInList.find((p: any) => p.id === pluginId);
	return pluginInfo ? pluginInfo.name : '未找到';
};
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;
		.el-table {
			flex: 1;
		}
	}
}
.layout-padding {
	padding: 0 15px 15px 15px !important;
	width: 100%;
}
</style>
